import pymysql
from fastapi import Depends
from utils import get_connection


def get_user(username):
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT username, password FROM user WHERE username = %s LIMIT 1", (username,))
    data = cursor.fetchone()
    cursor.close()
    conn.close()
    print('get_user', data)
    return data


def get_logging():
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT * FROM login_data")
    data = cursor.fetchall()
    cursor.close()
    conn.close()
    print('get_logging', data)
    return data


def create_table_login_data():
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute(
        "CREATE TABLE IF NOT EXISTS `login_data` (`id` INT AUTO_INCREMENT PRIMARY KEY, `username` VARCHAR(255) NOT NULL, `time` DATETIME)")
    cursor.close()
    conn.close()


def insert_login_data(username):
    from datetime import datetime
    current_time = datetime.now()
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("INSERT INTO `login_data` (`username`, `time`) VALUES (%s, %s)", (username, current_time))
    conn.commit()
    print("Data inserted:", (username, current_time))
    cursor.close()
    conn.close()


def get_login_data1():
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT username, time FROM login_data ORDER BY id DESC LIMIT 1")
    data = cursor.fetchone()
    cursor.close()
    conn.close()
    return data


def get_information(username):
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT id, username, email FROM information WHERE username = %s LIMIT 1", (username,))
    info = cursor.fetchone()
    cursor.close()
    conn.close()
    return info